package service

import (
	"fmt"
	"log"
	"strconv"
	"time"

	"gitee.com/chenxuan520/npyhomework/internal/config"
	"gitee.com/chenxuan520/npyhomework/internal/model"
	"github.com/tarm/serial"
)

var GlobalConfig Serial

func init() {
	c := &serial.Config{
		Name: config.GlobalConfig.Serial.Path,
		Baud: config.GlobalConfig.Serial.BaudRate,
	}

	var err error
	GlobalConfig.Serial, err = serial.OpenPort(c)
	if err != nil {
		panic(err)
	}
	log.Println("init success")
	go GlobalConfig.readData()
}

func (s *Serial) readData() {
	s.Serial.Write([]byte{1})
	head := make([]byte, 1)
	buf := make([]byte, 4)
	getTime := 0
	for {
		head[0] = 0
		for head[0] != 0xAA {
			_, err := s.Serial.Read(head)
			if err != nil {
				log.Fatal(err)
				break
			}
			if head[0] != 0xAA {
				log.Printf("get wrong\n")
			}
		}
		recvNum := 0
		for recvNum < 4 {
			buf[recvNum] = 0
			n, err := s.Serial.Read(head)
			if err != nil {
				log.Fatal(err)
				break
			}
			buf[recvNum] = head[0]
			recvNum += n
		}
		temperatureInt := int(buf[0])
		temperatureFloat := int(buf[1])
		wetInt := int(buf[2])
		wetFloat := int(buf[3])
		tempf, err := strconv.ParseFloat(fmt.Sprintf("%d.%d", temperatureInt, temperatureFloat), 64)
		if err != nil {
			log.Println(err)
		}
		wetf, err := strconv.ParseFloat(fmt.Sprintf("%d.%d", wetInt, wetFloat), 64)
		if err != nil {
			log.Println(err)
		}
		log.Printf("%d.%d %d.%d", temperatureInt, temperatureFloat, wetInt, wetFloat)
		data := model.Data{
			Temperature: tempf,
			Wet:         wetf,
			CreateTime:  time.Now().Unix(),
		}
		getTime += 1
		if getTime%config.GlobalConfig.Server.PickTime == 0 {
			err = data.Insert()
			if err != nil {
				log.Println(err)
			}
		}
	}

}

type Serial struct {
	Serial *serial.Port
}

func (s *Serial) WriteOper(oper OperType) error {
	_, err := s.Serial.Write([]byte{byte(oper)})
	return err
}
